package com.splic.api.controller.product;

import com.github.pagehelper.PageInfo;
import com.splic.common.core.controller.BaseController;
import com.splic.common.core.domain.ResponseObj;
import com.splic.common.utils.IpUtils;
import com.splic.common.utils.ShiroUtils;
import com.splic.common.utils.StringUtils;
import com.splic.product.domain.Order;
import com.splic.product.dto.CreateOrderDto;
import com.splic.product.dto.CreateOrderReturnDto;
import com.splic.product.dto.OrderDto;
import com.splic.product.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/order")
@Slf4j
public class  ApiOrderController extends BaseController {

    @Autowired
    private OrderService orderServiceImpl;
    /**
     * 创建订单
     *
     * @return
     */
    @PostMapping("/createOrder")
    public ResponseObj<CreateOrderReturnDto> createOrder(@RequestBody CreateOrderDto order, HttpServletRequest request) {
        try {
            if(order.getGoodsId() == null){
                return ResponseObj.ERROR("商品不能为空。");
            }
            order.setUserId(ShiroUtils.getUserId());
            order.setIp(IpUtils.getIpAddr(request));
            return ResponseObj.SUCCESS(orderServiceImpl.createOrder(order));
        }catch (Exception e){
            log.error("下单失败:{}",e);
            return ResponseObj.ERROR("下单失败");
        }
    }

    /**
     * 查看订单支付状态
     *
     * @return
     */
    @GetMapping("/checkOrder")
    public ResponseObj<Boolean> checkOrder(String orderNo) {
        try {
            if(StringUtils.isEmpty(orderNo)){
                return ResponseObj.ERROR("订单编号不能为空。");
            }
            return ResponseObj.SUCCESS(orderServiceImpl.checkOrder(orderNo));
        }catch (Exception e){
            log.error("订单状态查询失败:{}",e);
            return ResponseObj.ERROR("订单状态查询失败");
        }
    }


    /**
     * 获取我的订单列表
     *
     * @return
     */
    @GetMapping("/getOrderList")
    public ResponseObj<PageInfo<Order>> getOrderList() {
        try{
            startPage();
            OrderDto order = new OrderDto();
            order.setUserId(ShiroUtils.getUserId());
            List<Order> list = orderServiceImpl.selectOrderList(order);
            return ResponseObj.SUCCESS(new PageInfo(list));
        }catch (Exception e){
            log.error("查询订单列表失败:{}",e);
            return ResponseObj.ERROR("查询订单列表失败");
        }
    }
}
